package com.sleet.yuemiao.util;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;

@Slf4j
public class AESUtil {
    /**
     * 算法/模式/补码方式
     */
    public static final String AES_CBC_PKCS7 = "AES/CBC/PKCS7Padding";

    /**
     * 解决java不支持AES/CBC/PKCS7Padding模式解密
     */
    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 加密 + Base64
     *
     * @param iv 初始向量
     */
    public static String encryptString(byte[] data, String key, String iv) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_CBC_PKCS7);
        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS7);
        // CBC模式，需要向量iv，增加算法强度
        IvParameterSpec spec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);
        byte[] bytes = cipher.doFinal(data);
        return new String(Base64Utils.encode(bytes));
    }

    /**
     * 解密 + Base64
     *
     * @param iv 初始向量
     */
    public static String decryptString(byte[] data, String key, String iv) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_CBC_PKCS7);
        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS7,"BC");
        IvParameterSpec spec = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
        byte[] bytes = cipher.doFinal(data);
        return new String(bytes, "UTF-8");
    }
}